package com.lsy.renameAssistant;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.lsy.mysqlAssistant.domain.ChatMessages;
import com.lsy.mysqlAssistant.mapper.ChatMessagesMapper;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;

@Component
public class RenameChatMemoryStore implements ChatMemoryStore {

    @Autowired
    private ChatMessagesMapper chatMessagesMapper;

    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        LambdaQueryWrapper<ChatMessages> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ChatMessages::getMessageId,memoryId);
        lqw.last("limit 1");
        ChatMessages chatMessages = chatMessagesMapper.selectOne(lqw);
        if(chatMessages!=null){
            return ChatMessageDeserializer.messagesFromJson(chatMessages.getContent());
        }else {
            return new LinkedList<>();
        }
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> messages) {
        System.out.println(memoryId);
        LambdaQueryWrapper<ChatMessages> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ChatMessages::getMessageId,String.valueOf(memoryId));
        lqw.last("limit 1");
        ChatMessages chatMessages = chatMessagesMapper.selectOne(lqw);
        if(chatMessages!=null){

            chatMessages.setContent(ChatMessageSerializer.messagesToJson(messages));
            chatMessagesMapper.updateById(chatMessages);
        }else {
            ChatMessages newChatMessages = new ChatMessages();
            newChatMessages.setMessageId(String.valueOf(memoryId));
            newChatMessages.setContent(ChatMessageSerializer.messagesToJson(messages));
            chatMessagesMapper.insert(newChatMessages);

        }




    }

    @Override
    public void deleteMessages(Object memoryId) {
        LambdaQueryWrapper<ChatMessages> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ChatMessages::getMessageId,memoryId);
        lqw.last("limit 1");
        chatMessagesMapper.delete(lqw);
    }


}